package com.itwenke.springbootdemo.shirowebssm.realm;

import com.alibaba.druid.util.StringUtils;
import com.itwenke.springbootdemo.shirowebssm.entity.Permission;
import com.itwenke.springbootdemo.shirowebssm.entity.Role;
import com.itwenke.springbootdemo.shirowebssm.entity.User;
import com.itwenke.springbootdemo.shirowebssm.service.PermissionService;
import com.itwenke.springbootdemo.shirowebssm.service.RoleService;
import com.itwenke.springbootdemo.shirowebssm.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;


    {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(1024);
        this.setCredentialsMatcher(matcher);
    }

    /**
     * 用户认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户名
        String username = (String) authenticationToken.getPrincipal();

        // 判断用户名（非空）
        if(StringUtils.isEmpty(username)){
            // 返回null，默认抛出一个异常：org.apache.shiro.authc.UnknownAccountException
            return null;
        }

        // 根据用户名查询用户
        User user = userService.findByUsername(username);

        // 判断用户是否为null
        if(user == null) {
            return null;
        }

        // 声明 SimpleAuthenticationInfo 对象，并填充用户信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(),"CustomRealm");

        // 设置盐
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));

        return simpleAuthenticationInfo;
    }

    /***
     * 授权认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取认证用户
        User user = (User) principalCollection.getPrimaryPrincipal();

        // 根据用户获取当前用户拥有的角色
        Set<Role> roleSet = roleService.findRolesByUid(user.getId());
        Set<Long> roleIdSet = new HashSet<>();
        Set<String> roleNameSet = new HashSet<>();
        for (Role role : roleSet) {
            roleIdSet.add(role.getId());
            roleNameSet.add(role.getRoleName());
        }

        // 根据用户拥有的角色查询权限信息
        Set<Permission> permSet = permissionService.findPermsByRoleSet(roleIdSet);
        Set<String> permNameSet = new HashSet<>();
        for (Permission permission : permSet) {
            permNameSet.add(permission.getPermName());
        }


        // 声明 SimpleAuthorizationInfo 对象，并填充角色信息和权限信息
        SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();
        simpleAuthenticationInfo.setRoles(roleNameSet);
        simpleAuthenticationInfo.setStringPermissions(permNameSet);

        return simpleAuthenticationInfo;
    }
}
